import axios from 'axios'
import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    config.data = qs.stringify(config.data)
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    const { code, message, data } = res
    switch (code) {
      case 0: return res.data
      case 10001:
        {
          MessageBox.confirm('您的帐号被禁用！', '请联系系统管理员', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
          break
        }
      default:
        {
          let sms = 'Error'
          if (code == 10000) { sms = data } else { sms = message }
          Message({
            message: sms,
            type: 'error',
            duration: 3 * 1000
          })
          return Promise.reject(new Error(sms))
        }
    }
  },
  error => {
    const status = error.response.status
    switch (status) {
      case 403:
        {
          MessageBox.confirm('您的登陆信息过期！', '请您重新登陆', {
            confirmButtonText: '重新登陆',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
          break
        }
      default:
        {
          console.log('err' + error.message) // for debug
          Message({
            message: error.message,
            type: 'error',
            duration: 3 * 1000
          })
          break
        }
    }
    return Promise.reject(error)
  }
)

export default service
